<template>
  <el-drawer
    title="支付订单"
    :visible="show"
    @close="(e) => $emit('update:show', e)"
    direction="btt"
    append-to-body
    size="80vh"
  >
    <div class="pay-view" v-if="isSuccess">
      <el-descriptions
        class="margin-top"
        :column="4"
        size="medium"
        border
        direction="vertical"
      >
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-user"></i>
            订单号
          </template>
          {{ order.id || "" }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-user"></i>
            用户名
          </template>
          {{ user.name || "" }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-s-order"></i>
            订单类型
          </template>
          {{
            order.type == 1
              ? "保洁订单"
              : order.type == 2
              ? "点餐订单"
              : "陪护订单"
          }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-mobile-phone"></i>
            联系方式
          </template>
          {{ order.phone || "" }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label"> 金额 </template>
          ￥ {{ order.jiner || "0.00" }} 元
        </el-descriptions-item>
      </el-descriptions>

      <div class="pay-but-view">
        <el-button
          type="primary"
          round
          class="w-full"
          style="padding: 15px 0"
          @click="payClick"
          >确认付款</el-button
        >
        <el-button
          type="info"
          round
          class="w-full"
          plain
          style="padding: 15px 0; margin-left: 0"
          @click="$emit('update:show', false)"
          >取消</el-button
        >
      </div>
    </div>

    <div v-else>
      <div class="pay-view admin" @contextmenu.prevent="isadminbut = true">
        <div v-if="isadminbut" class="flex-center admin">
          <div>
            <h3>输入管理员密码：支付成功模拟</h3>
            <br />
            <el-input v-model="inputAdmin" class="w-500"></el-input>
          </div>
        </div>
        <div v-else class="flex-center admin">
          <h1>正在支付中...</h1>
        </div>
      </div>
    </div>
  </el-drawer>
</template>

<script>
import dayjs from "dayjs";
function generateRandomString() {
  return (
    Math.random().toString(36).substring(2, 15) +
    Math.random().toString(36).substring(2, 15)
  );
}

function formatAmount(amount) {
  // 正则表达式匹配格式：整数部分任意长度，小数部分恰好两位
  const regex = /^\d+(\.\d{2})?$/;

  // 测试字符串是否符合正则表达式
  if (regex.test(amount)) {
    // 如果已经有两位小数，直接返回
    if (amount.includes(".") && amount.split(".")[1].length === 2) {
      return amount;
    }
  }

  // 没有两位小数，进行补位
  let [integerPart, decimalPart] = amount.split(".");
  if (!decimalPart) {
    // 没有小数部分，补两位0
    return `${integerPart}.00`;
  } else if (decimalPart.length === 1) {
    // 有一位小数，补一位0
    return `${integerPart}.${decimalPart}0`;
  } else {
    // 小数部分超过两位，截取前两位
    return `${integerPart}.${decimalPart.slice(0, 2)}`;
  }
}

function getRandomNumberString(length) {
  let result = "";
  const characters = "0123456789";
  for (let i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * characters.length));
  }
  return result;
}
export default {
  props: {
    show: Boolean,
    title: {
      type: String,
      default: "",
    },
    orderData: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      user: JSON.parse(localStorage.getItem("xm-user") || "{}"),
      order: {},
      paydata: {
        out_trade_no: "",
        total_amount: "",
        subject: "",
      },
      isSuccess: true,
      isadminbut: false,
      inputAdmin: "",
    };
  },
  watch: {
    show() {
      this.order = this.orderData;
    },
    inputAdmin(value) {
      if (value === "admin") {
        this.$router.push({
          name: "pay-success",
          query: {
            out_trade_no: this.paydata.out_trade_no,
            total_amount: this.paydata.total_amount,
            gmt_payment: dayjs().format("YYYY-MM-DD HH:mm:ss"),
            id: this.order.id,
            type: this.order.type,
          },
        });
      }
    },
  },
  methods: {
    payClick() {
      const ordertype =
        this.order.type == 1
          ? "保洁订单"
          : this.order.type == 2
          ? "点餐订单"
          : "陪护订单";
      this.paydata.out_trade_no = `2024${getRandomNumberString(10)}_${
        this.order.id
      }_${generateRandomString()}`;
      this.paydata.total_amount = formatAmount(this.order.jiner);
      this.paydata.subject = this.getTypeText(ordertype, "养老");

      const params = new URLSearchParams();
      for (const key in this.paydata) {
        params.append(key, this.paydata[key]);
      }
      // window.location.href = `http://localhost:9090/alipay/pay?${params.toString()}`;
      window.open(`http://localhost:9090/alipay/pay?${params.toString()}`);
      this.isSuccess = false;
    },

    getTypeText(type, state = "", end = "") {
      let typeText =
        type == 1 ? "保洁订单" : type == 2 ? "点餐订单" : "陪护订单";
      return state + typeText + end;
    },
  },
};
</script>

<style lang="scss" scoped>
.pay-view {
  position: relative;
  height: 100%;
  padding: 0 20px;
}
.pay-but-view {
  position: absolute;
  bottom: 20px;
  left: 0;
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 10px;
  padding: 0 1vw;
}

::v-deep .el-descriptions-row {
  height: 70px;
  font-size: 26px;
}

::v-deep .el-descriptions-row .el-descriptions-item__cell {
  text-align: center;
}

.admin {
  width: 100%;
  height: 60vh;
}
</style>
